#!/bin/sh /etc/rc.common

START=95
USE_PROCD=1

append_arg() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get val "$cfg" "$var"
	[ -n "$val" -o -n "$def" ] && procd_append_param command $opt "${val:-$def}"
}

append_bool() {
	local cfg="$1"
	local var="$2"
	local opt="$3"
	local def="$4"
	local val

	config_get_bool val "$cfg" "$var" "$def"
	[ "$val" = 1 ] && procd_append_param command "$opt"
}

start_instance() {
	local cfg="$1"
	local aux

	config_get_bool aux "$cfg" 'disabled' '0'
	[ "$aux" = 1 ] && return 1

	procd_open_instance

	procd_set_param command /usr/sbin/minisatip
	procd_append_param command "-f"

	append_arg "$cfg" simulate_fontends "-a"
	append_arg "$cfg" adapter_buffers "--buffers"
	append_arg "$cfg" socket_write_buffer "-B"
	append_arg "$cfg" diseqc "--diseqc"
	append_arg "$cfg" diseqc_timing "--diseqc-timing"
	append_arg "$cfg" server_id "--device-id"
	append_bool "$cfg" send_encrypted "-E"
	append_arg "$cfg" delsys "--delsys"
	append_arg "$cfg" dmx_source "--dmx-source"
	append_arg "$cfg" enabled_adapters "--enable-adapter"
	append_arg "$cfg" dvr_priority "--priority"
	append_arg "$cfg" lnb "--lnb"
	append_arg "$cfg" mac_address "-m"
	append_arg "$cfg" power_management "--nopm"
	append_arg "$cfg" dvbapi_url "--dvbapi"
	append_arg "$cfg" playlist_url "-p"
	append_arg "$cfg" udp_port "-P"
	append_arg "$cfg" remote_rtp_host "--remote-rtp"
	append_arg "$cfg" document_root "--document-root"
	append_bool "$cfg" satip_tcp "--satip-tcp"
	append_arg "$cfg" slave_adapters "--slave"
	append_arg "$cfg" clean_psi "--cleanpsi"
	append_bool "$cfg" threads "--threads"
	append_arg "$cfg" unicable_string "--unicable"
	append_arg "$cfg" jess_string "--jess"
	append_arg "$cfg" xml_url "--http-host"
	append_arg "$cfg" http_port "--http-port"
	append_arg "$cfg" xml_path "--xml"
	append_arg "$cfg" rtsp_port "--rtsp_port"

	config_get_bool aux "$cfg" 'respawn' '0'
	[ "$aux" = 1 ] && procd_set_param respawn

	procd_close_instance
}

service_triggers() {
	procd_add_reload_trigger "minisatip"
}

start_service() {
	config_load minisatip
	config_foreach start_instance minisatip
}
